/*
 * MIT License
 *
 * Copyright (c) 2025 Mark·虎
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package com.hsxxherp.key.support;

import com.hsxxherp.key.support.sys.entity.SysCodeRuleConfig;
import com.hsxxherp.key.support.sys.entity.SysSerialNumberRecord;
import com.hsxxherp.key.support.sys.mapper.SysCodeRuleConfigMapper;
import com.hsxxherp.key.support.sys.mapper.SysSerialNumberRecordMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * 编码生成服务
 * <p>
 * 更具配置生成bean 实体编码，非主键编码
 * </p>
 *
 * @author Mark·虎克（2486970363@qq.com）
 * @since 2025-2-23
 */
@Component
public class CodeGenerator {
    @Autowired
    private SysCodeRuleConfigMapper codeRuleConfigMapper;
    @Autowired
    private SysSerialNumberRecordMapper serialNumberRecordMapper;

    /**
     * 实体赋值
     *
     * @param entity 实体类对象
     */
    public void generateAndAssignCode(Object entity) {
        String entityClassName = entity.getClass().getName();

        SysCodeRuleConfig config = codeRuleConfigMapper.findByEntityClassNameAndIsEnabledTrue(entityClassName);
        if (config == null) {
            throw new IllegalArgumentException("未找到该实体类的启用编码规则配置");
        }

        String code = generateCode(config);

        try {
            Field codeField = entity.getClass().getDeclaredField(config.getCodeFieldName());
            codeField.setAccessible(true);
            codeField.set(entity, code);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException("无法将生成的编号赋值到指定字段", e);
        }
    }

    /**
     * 生成编码
     *
     * @param config 编码规则配置
     * @return 生成的编码
     */
    private String generateCode(SysCodeRuleConfig config) {
        StringBuilder code = new StringBuilder();

        // 添加单据前缀
        if (config.getPrefix() != null && !config.getPrefix().isEmpty()) {
            code.append(config.getPrefix());
        }

        // 添加日期
        if (config.getDateFormat() != null && !config.getDateFormat().isEmpty()) {
            SimpleDateFormat sdf = new SimpleDateFormat(config.getDateFormat());
            code.append(sdf.format(new Date()));
        }

        // 添加流水号或随机数
        if (config.getUseSerialNumber()) {
            int serialNumber = getNextSerialNumber(config.getPrefix());
            code.append(String.format("%06d", serialNumber));
        } else {
            Random random = new Random();
            for (int i = 0; i < config.getRandomNumberLength(); i++) {
                code.append(random.nextInt(10));
            }
        }

        return code.toString();
    }

    /**
     * 获取下一个流水号
     *
     * @param prefix 前缀
     * @return 下一个流水号
     */
    private int getNextSerialNumber(String prefix) {
        SysSerialNumberRecord record = serialNumberRecordMapper.findByPrefix(prefix);
        if (record == null) {
            record = new SysSerialNumberRecord();
            record.setPrefix(prefix);
            record.setCurrentNumber(1);
            serialNumberRecordMapper.insert(record);
            return 1;
        }
        int currentNumber = record.getCurrentNumber();
        record.setCurrentNumber(currentNumber + 1);
        serialNumberRecordMapper.insert(record);
        return currentNumber + 1;
    }
}